package com.java.servlet;

import java.io.IOException;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.java.bean.LoginBean;

/**
 * Servlet implementation class LoginAction
 */
@WebServlet("/LoginAction")
public class LoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginAction() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(name + password);
		ResultSet set = LoginBean.login(name, password);

		try {
			if (set.next()) {
				String id = set.getString("id");
				String username = set.getString("username");
				System.out.println(id);
				Cookie cookie = new Cookie("id", id);
				cookie.setMaxAge(30 * 24 * 60 * 62);
				response.addCookie(cookie);
				cookie = new Cookie("username", username);
				cookie.setMaxAge(30 * 24 * 60 * 62);
				response.addCookie(cookie);
				response.sendRedirect("./index.jsp");
			} else {
				request.setAttribute("hint", "retry");
				request.getRequestDispatcher("/login.jsp").forward(request,
						response);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
